package com.example.prompt.controller;

import com.example.prompt.service.file.FileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件处理
 */

@Slf4j
@RestController
@RequestMapping("/api/file")
@RequiredArgsConstructor
public class FileController {

    private final FileService fileService;

    // 10M
    private static final long MAX_FILE_SIZE = 100 * 1000 * 1024;

    @PostMapping("/upload")
    public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) {
        log.info("文件上传开始");
        if (file.isEmpty()) {
            return new ResponseEntity<>("请选择一个文件进行上传", HttpStatus.BAD_REQUEST);
        }

        // 检查文件类型
        String contentType = file.getContentType();
        if (!"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".equals(contentType) &&
                !"text/plain".equals(contentType)) {
            return new ResponseEntity<>("仅支持上传 Excel (.xlsx) 或 txt 文件", HttpStatus.BAD_REQUEST);
        }

        // 检查文件大小
        if (file.getSize() > MAX_FILE_SIZE) {
            return new ResponseEntity<>("文件大小不能超过 10M", HttpStatus.BAD_REQUEST);
        }
        String fileName = fileService.uploadFile(file);
        if(StringUtils.isEmpty(fileName)){
            return new ResponseEntity<>("文件上传失败", HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity<>(fileName, HttpStatus.OK);
    }

}
